package com.max.mil.common.util;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

@SuppressWarnings("serial")
public class PageTag extends TagSupport 
{

	private int pageNo;
	
	private int pageSize;
	
	private int totalCount;
	
	private String url;
	
	public int doStartTag() throws JspException
	{
		try
		{
			JspWriter out = this.pageContext.getOut();
			StringBuffer sb = new StringBuffer();
			
			int totalPage = (int) Math.ceil(totalCount * 1.000 / this.pageSize);
			boolean hasPrev = pageNo>1;
			boolean hasNext = pageNo<totalPage;
			url = url.replaceAll("&pageNo=\\d+", "").replaceAll("&pageSize=\\d+", "");
			
			sb.append("<ul class=\"pagination\">");
			sb.append("<li><a href=\""+url+"&"+"pageNo=1"+"&pageSize="+pageSize+"\">&laquo;</a></li>");
			for(int pageNoTmp=1; pageNoTmp<=totalPage; pageNoTmp++)
				sb.append(pageNo==pageNoTmp?"<li class=\"active\">":"<li>")
				  .append("<a href=\""+url+"&"+"pageNo="+pageNoTmp+"&pageSize="+pageSize+"\">"+pageNoTmp+"</a>")
				  .append("</li>");
			sb.append("<li><a href=\""+url+"&"+"pageNo="+totalPage+"&pageSize="+pageSize+"\">&raquo;</a></li>");
			sb.append("</ul>");
			
			out.println(sb.toString());
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		
		return SKIP_BODY;
	}

	public void setPageNo(int pageNo)
	{
		this.pageNo = pageNo;
	}

	public void setPageSize(int pageSize)
	{
		this.pageSize = pageSize;
	}

	public void setTotalCount(int totalCount)
	{
		this.totalCount = totalCount;
	}

	public void setUrl(String url)
	{
		this.url = url;
	}
}
